<?php
namespace app\api\controller\kupay;

use app\common\controller\Api;
use think\Db;
use app\common\library\kupay\Sms;
use think\Session;

/**
 * 示例接口
 */
class Crontabs extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';
    public function _initialize()
    {
        parent::_initialize();
        $sapi_type =$_SERVER['HTTP_USER_AGENT'];
        $a='curl';
        if(strpos($sapi_type,$a) !== false){

        } else{
            $this->error('权限错误！请在服务器端运行');
        }
    }
    public function index(){
        $times=time();
        $setlog = Db::name('kupay_setlog')->where('timing','<',$times)->where('static',1)->where('timing','<>','')->select();
        $a=[];
        foreach($setlog as $k=>$v){
            $a[]= $this->sends($v['id']);
        }
        return 1;
    }


    //    总发送
    protected function sends($id)
    {
        $input['id'] = $id;
        $company = Db::name('kupay_compay')->find();
        $paylog = Db::name('kupay_paylog')->where('pid', $input['id'])->select();
        $setlog = Db::name('kupay_setlog')->where('id', $input['id'])->find();
        if($setlog['static']!=1){
            return  '';
        }
        Db::name('kupay_setlog')->where('id', $input['id'])->update(['static'=>2]);
        $oks = 0;
        $errs = 0;

        foreach ($paylog as $k => $v) {

            $static = 0;
            if ($v['type'] == 1) {
                $static = $this->weixin($v['id']);
            }else if ($v['type'] == 4) {
                $msgs = '{"name":"' . $v['name'] . '-' . $company['company'] . '","time":"' . $setlog['times'] . '","content":"' . $setlog['type'] . '","code":"index/kupay/index"}';
                $static = $this->duanxin($v['phone'], $msgs);
            }



            if ($static == 0) {
                $errs = $errs + 1;
            } else {
                $oks = $oks + 1;
                $data = [
                    'updatetime' => time(),
                    'status' => $static,
                ];
                Db::name('kupay_paylog')->where('id', $v['id'])->update($data);
            }
        }
        $datas=['timing'=>'','static'=>3];
        Db::name('kupay_setlog')->where('id', $input['id'])->update($datas);
        return $errs;
    }


    protected function duanxin($tel, $vcode)
    {
        $sms = new Sms();

//测试模式
        $results = $sms->send_verify($tel, $vcode);
        if ($results) {
            return 1;
        } else {
            return 0;
        }
    }



//    微信发送
    protected function weixin($id)
    {
        $weixin = Db::name('kupay_config')->where('name', 'weixin')->find();
        $weixin = unserialize($weixin['value']);
        $paylog = Db::name('kupay_paylog')->where('id', $id)->find();
        $setlog = Db::name('kupay_setlog')->where('id', $paylog['pid'])->find();
        $user = Db::name('kupay_user')->where('phone', $paylog['phone'])->find();
        if (empty($user) || empty($user['openid'])) {
            return 0;
        }
        $times = date('Y-m-d H:i:s', time());
        $appid = $weixin['appid'];
        $secret = $weixin['appsecret'];
        $appinfo = $weixin['appinfo'];
        $types = isset($weixin['types']) ? $weixin['types'] : 1;//控制新版，还是旧版
        $time = date('Y-m-d H:i:s', time());
        $urls = request()->domain().'/index/kupay/index';
        if ($types == 1) {
            $template = [
                'touser' => $user['openid'],
                'template_id' => $appinfo, // 填写你自己的消息模板ID
                'url' => $urls,
                'data' => [ // 模板消息内容，根据模板详情进行设置
                    'keyword1' => ['value' => urlencode($paylog['name'])],
                    'keyword2' => ['value' => urlencode($setlog['times'])],
                    'keyword3' => ['value' => urlencode($times)],
                ],
            ];
        } else {
            $template = [
                'touser' => $user['openid'],
                'template_id' => $appinfo, // 填写你自己的消息模板ID
                'url' => $urls,
                'data' => [ // 模板消息内容，根据模板详情进行设置
                    'thing8' => ['value' => urlencode($paylog['company'])],
                    'time3' => ['value' => urlencode($setlog['times'])],
                    'time5' => ['value' => urlencode($times)],
                ],
            ];
        }
        $json_template = json_encode($template);
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
        $access_token = '';
        if (Session::has('access_tokens')) {
            if (empty(Session::get('access_tokens'))) {
                $access_token = json_decode(self::curl_post($url), true);
                $access_token = $access_token['access_token'];
                Session::set('access_token_times', time() + 100);
                Session::set('access_tokens', $access_token);
            } else {
                if (Session::get('access_token_times') < time()) {
                    $access_token = Session::get('access_tokens');
                } else {
                    $access_token = json_decode(self::curl_post($url), true);
                    $access_token = $access_token['access_token'];
                    Session::set('access_token_times', time() + 100);
                    Session::set('access_tokens', $access_token);
                }
            }

        } else {
            $access_token = json_decode(self::curl_post($url), true);
            $access_token = $access_token['access_token'];
            Session::set('access_token_times', time() + 100);
            Session::set('access_tokens', $access_token);
        }
        $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
        $dataRes = $this->curl_post($url, urldecode($json_template));
        $dataRes = json_decode($dataRes, true);
        if ($dataRes['errcode'] == 0) {
            return 1;
        } else {
            return 0;
        }


    }


    protected function curl_post($url, $data = array())
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// POST数据
        curl_setopt($ch, CURLOPT_POST, 1);
// 把post的变量加上
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

}
